<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-24
 * Time: 上午 11:10
 */

namespace App\Lib\DingDingNotice;


class BaseNotice
{
    protected $template = [];
    protected $webhook = 'https://oapi.dingtalk.com/robot/send?access_token=';
    protected $atMobiles = [];
    protected $isAtall = false;
    protected $token = '';
    /*
     * 发送钉钉通知 文本格式
     * */
    public function sendMessage()
    {
        $webhook = $this->webhook.$this->token;
        $data = array(
            'msgtype' => 'text',
            'text' => array(
                'content' => $this->template
            ),
            "at" => array(
                "atMobiles" => $this->atMobiles,
                "isAtAll" => $this->isAtall
            )
        );
        $data_string = json_encode($data);
        $result = $this->request_by_curl($webhook, $data_string);
        return $result;
    }

    /*
     *发送钉钉通知 markdown格式
     * */
    public function sendMarkdownMessage()
    {
        $webhook = $this->webhook.$this->token;
        $data = array(
            'msgtype' => 'markdown',
            'markdown' => $this->template,
            "at" => array(
                "atMobiles" => $this->atMobiles,
                "isAtAll" => $this->isAtall
            )
        );
        $data_string = json_encode($data);
        $result = $this->request_by_curl($webhook, $data_string);
        return $result;
    }

    function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}